package cao.oschina.function.tweet;

import android.support.v4.view.ViewPager;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import cao.oschina.R;
import cao.oschina.function.FunctionFragment;
import cao.oschina.ui.Main;
import hd.util.adapter.pager.BasePagerAdapter;
import hd.util.widget.PagerTabView;

/**
 * 动弹
 * <p/>
 * Created by Haidy on 15/4/3.
 */
public class TweetFragment extends FunctionFragment {

    private ViewPager newsPager;
    private List<View> views;
    private TweetFunction[] functions = new TweetFunction[3];

    public TweetFragment(Main main) {
        super(main);
    }

    /**
     * 要创建的视图
     *
     * @return view
     */
    @Override
    protected int createView() {
        return R.layout.tweet_view;
    }

    /**
     * 初始化界面
     *
     * @param view view
     */
    @Override
    protected void initView(View view) {
        newsPager = (ViewPager) view.findViewById(R.id.tweet_pager);
        views = new ArrayList<>();
        views.add(View.inflate(app, R.layout.tweet_list_view, null));
        views.add(View.inflate(app, R.layout.tweet_list_view, null));
        views.add(View.inflate(app, R.layout.tweet_list_view, null));
        newsPager.setAdapter(new BasePagerAdapter(views));
        final PagerTabView pagerTabView = (PagerTabView) view.findViewById(R.id.pagerTabView);
        newsPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            private int pageWidth = app.getScreenWidth();

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                int offsetPixels = position * pageWidth + positionOffsetPixels;
                pagerTabView.scrollBarScrollTo(-offsetPixels / views.size());
            }

            @Override
            public void onPageSelected(int position) {
                if (functions[position] == null) {
                    if (position == 1) {
                        functions[position] = new TweetFunction(views.get(position), main, TweetFunction.TYPE_HOT);
                    } else if (position == 2) {
                        functions[position] = new TweetFunction(views.get(position), main, TweetFunction.TYPE_ME);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        pagerTabView.setOnCheckedChangeListener(new PagerTabView.OnCheckedChangeListener() {
            @Override
            public void onChecked(View view) {
                int index = view.getId() - R.id.news;
                newsPager.setCurrentItem(index);
            }
        });
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        functions[0] = new TweetFunction(views.get(0), main, TweetFunction.TYPE_LATEST);
    }
}
